<?php

namespace app\api\service\event;

use app\api\model\event\Account;
use app\api\model\event\Event;
use app\api\service\token\LoginToken;
use app\lib\douyin\douyin;
use app\lib\exception\event\ReleaseException;
use think\Db;
use think\Exception;
use app\lib\integral\Integral;
use app\api\model\template\User;

class ReleaseService extends Integral
{
    private static $instance;

    public static function getInstance(): ReleaseService
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }


    /**
     * @param $params
     * @throws ReleaseException
     */
    public function getEventList($params){
        $pageSize = $params['pageSize']??20;
        $login = LoginToken::getInstance();
        $uid = $login->getCurrentUid();
        $gid = $login->getCurrentGid();

        $app_ids = Account::field('app_id');
        if ($uid !=1 && $gid!=2){
            $app_ids->where("uid",$uid);
        }
        $app_id = $app_ids->select()->toArray();
        $app_arr = [];
        foreach ($app_id as $v){
            $app_arr[] = $v['app_id'];
        }
        # 人工发布
        $event = Event::field("any_value(id)as id,
        any_value(title)as title,any_value(content)as content,
        any_value(images)as images,any_value(type)as type,group_id")
            ->with(['name'])->where("pub_type",2)
            ->whereIn("app_id",$app_arr);
        if (isset($params['status'])){
            $event->where("status",$params['status']);
        }
        if (!empty($params['start_time']) && !empty($params['end_time'])){
            $event->whereBetweenTime('update_time',$params['start_time'],$params['end_time']);
        }
        if (isset($params['backfill_type'])){
            if ($params['backfill_type'] == 1){
                $event->whereNotNull('backfill_url');
            }else if ($params['backfill_type'] == 2){
                $event->whereNull('backfill_url');
            }
        }
        if (isset($params['check'])){
            $event->where("check",$params['check']);
        }
        $list =  $event->order("id desc")->group("group_id")->paginate($pageSize)->each(function ($item){
            if (!empty($item->backfill_url)){
                $item->backfill_type = 1;
            }else{
                $item->backfill_type = 0;
            }
            $item->unclaimed = Event::where("group_id",$item->group_id)->where("status",1)->count();
        });
        return $list;
    }

    /**
     * @param $params
     * @throws ReleaseException
     */
    public function getEventGroupList($params){
        $pageSize = $params['pageSize']??20;
        $login = LoginToken::getInstance();
        $uid = $login->getCurrentUid();
        $gid = $login->getCurrentGid();

        $app_ids = Account::field('app_id');
        if ($uid !=1 && $gid!=2){
            $app_ids->where("uid",$uid);
        }
        $app_id = $app_ids->select()->toArray();
        $app_arr = [];
        foreach ($app_id as $v){
            $app_arr[] = $v['app_id'];
        }

        $list = Event::field("*")
            ->with(['name'])->where("pub_type",2)
            ->whereIn("app_id",$app_arr)
            ->where("group_id",$params['group_id'])
            ->select()->toArray();
        return $list;

    }


    /**
     * @param $params
     * @throws ReleaseException
     */
    public function backfillUrl($params){
        $event = Event::where("id",$params['id'])->where("status",1)->findOrEmpty();
        if ($event->isEmpty()){
            throw new ReleaseException([
                'msg' => '文章不存在',
                'error_code' => 20001
            ]);
        }
        if ($event->source_platform == '小红书'){
            $is = strstr($params['url'], '小红书');
            if ($is){
                $rs_1 = substr($params['url'],strpos($params['url'],"http"));
                $rs_2 = substr($rs_1,0,strpos($rs_1,"，"));
                $params['url'] = $rs_2;
            }
        }elseif ($event->source_platform == '逛逛号'){
            $is_1 = strstr($params['url'], '淘宝');
            $is_2 = strstr($params['url'], 'TA的内容超级棒');
            if ($is_1 || $is_2){
                $rs_1 = substr($params['url'],strpos($params['url'],"https"));
                $rs_2 = substr($rs_1,0,strpos($rs_1," "));
                $params['url'] = $rs_2;
            }
        }

        DB::startTrans();
        try {

            $data = [
                "backfill_url"=>$params['url'],
                "status"=>3,
                "check"=>0,
            ];
            $event->save($data);
            // 提交事务
            Db::commit();
        } catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new ReleaseException([
                'msg' => '文章回填失败',
                'error_code' => 20002
            ]);
        }
    }

//    /**
//     * @param $params
//     * @throws ReleaseException
//     */
//    public function douyinDistribute($params){
//        $event = Event::where("id",$params['id'])->where("status",1)->where("type",1)->findOrEmpty();
//        if ($event->isEmpty()){
//            throw new ReleaseException([
//                'msg' => '文章不存在',
//                'error_code' => 20001
//            ]);
//        }
//
//        $imgs = str_replace(' ','',$event->images);
//        #分享抖音号
//        $ticket = $this->ticket();
//        $attributes = [
//            "nonce_str"=>$this->generateRandomString(),
//            "ticket"=>$ticket,
//            "timestamp"=>(string)time()
//        ];
//        $sign = $this->createSign($attributes);
//        $attributes["signature"] = $sign;
//        $Not_necessary = [
//            "state"=>$this->share_id(),
//            "title"=>$event->title
//        ];
//        $baseUrl = $this->publishingContent($attributes,$Not_necessary);
//        $data = [
//            "baseUrl"=>$baseUrl,
//            "image_list_path"=>$imgs
//        ];
//        DB::startTrans();
//        try {
//            if (!empty($data['baseUrl'])){
//                $info = [
//                    'share_id'=>$Not_necessary['state'],
//                    "status"=>2
//                ];
//                $event->save($info);
//            }
//            // 提交事务
//            Db::commit();
//        } catch (Exception $e){
//            // 回滚事务
//            Db::rollback();
//            throw new ReleaseException([
//                'msg' => '文章回填失败',
//                'error_code' => 20002
//            ]);
//        }
//        return $data;
//    }
//
//    /**
//     * @param $params
//     * @throws ReleaseException
//     */
//    public function douyinChallenge($params){
//        $share_id = $params['content']['share_id']??0;
//        $video_id = $params['content']['video_id']??"";
//        $event = Event::where("share_id",$share_id)->where("source_platform","抖音号")->findOrEmpty();
//        if (!$event->isEmpty()){
//            DB::startTrans();
//            try {
//                $info = [
//                    "status"=>3,
//                    "backfill_url"=>$video_id,
//                ];
//                $event->save($info);
//                // 提交事务
//                Db::commit();
//            } catch (Exception $e){
//                // 回滚事务
//                Db::rollback();
//                throw new ReleaseException([
//                    'msg' => '文章回填失败',
//                    'error_code' => 20002
//                ]);
//            }
//        }
//    }


    /**
     * @param $params
     * @throws ReleaseException
     */
    public function follow($params){
        $openid = $this->getUnionidInfo($params['code']);

        $user = User::where('unionid',$openid['unionid'])->where('subscribe',1)->findOrEmpty();
        if ($user->isEmpty()){
            throw new ReleaseException([
                'msg' =>"未关注公众号",
                'error_code' => "2001"
            ]);
        }
    }


    /**
     * @param $params
     * @throws ReleaseException
     */
    public function bindAccount($params){
        $openid = $this->getUnionidInfo($params['code']);

        $login = LoginToken::getInstance();
        $uid = $login->getCurrentUid();
        $lin_user = Db::table('lin_user')->where("id",$uid)->find();
        if ($lin_user && !empty($lin_user['unionid'])){
            throw new ReleaseException([
                'msg' =>"账号已绑定公众号",
                'error_code' => 2001
            ]);
        }
        $unionid_user = Db::table('lin_user')->where("unionid",$openid['unionid'])->find();
        if ($unionid_user){
            throw new ReleaseException([
                'msg' =>"当前微信公众号，已被账号绑定",
                'error_code' => 2002
            ]);
        }
        DB::startTrans();
        try {
            Db::table('lin_user')->where("id",$uid)->update(['unionid'=>$openid['unionid']]);
            Db::commit();
        } catch (Exception $e){
                // 回滚事务
                Db::rollback();
                throw new ReleaseException([
                    'msg' => '绑定失败',
                    'error_code' => 20003
                ]);
        }
    }


    /**
     * @param $params
     * @throws ReleaseException
     */
    public function getBindAccount($params){
        $openid = $this->getUnionidInfo($params['code']);

        $unionid_user = Db::table('lin_user')->where("unionid",$openid['unionid'])->findOrEmpty();
        if ($unionid_user->isEmpty()){
            throw new ReleaseException([
                'msg' =>"当前账号未绑定",
                'error_code' => 2002
            ]);
        }
    }

    /**
     * @param $params
     * @throws ReleaseException
     */
    public function getIntegral($params){
        $login = LoginToken::getInstance();
        $uid = $login->getCurrentUid();
        $integral = \app\api\model\event\Integral::field('integral')->where("uid",$uid)->find();
        return $integral;
    }


    private function getUnionidInfo($code){
        $openid = $this->getOpenId($code);
        if (!empty($openid['errcode']) && $openid['errcode'] !=0){
            throw new ReleaseException([
                'msg' =>$openid['errmsg'],
                'error_code' => $openid['errcode']
            ]);
        }
        return $openid;
    }
}
